# -----------------------------------------------------------------------------
# @author soap.zhao
# This is code of markdown generating by ply
# @update 2015-1-10
# -----------------------------------------------------------------------------
import sys

tokens = (
    'H1','H2','H3', 'CR', 'TEXT', 'STRONG1', 'STRONG2', 'EM1', 'EM2', 'LINE1', 'LINE2', 'UNLINE'
    )

# Tokens
t_H1 = r'\# '
t_H2 = r'\#\# '
t_H3 = r'\#\#\# '
t_STRONG1 = r'\*\*'
t_EM2 = r'\*'
t_EM1 = r'\_'
t_STRONG2 = r'\_\_'
t_LINE1 = r'\-\-\-'
t_LINE2 = r'\*\ \*\ \*'
t_UNLINE = r'\=\=\='

#t_IMG = r'\!'

def t_TEXT(t):
    r'[a-zA-Z ,.:/\']+'
    t.value = str(t.value)
    return t

t_ignore = " \t"

def t_CR(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")
    return t

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
from ply import ply.lex as lex
lex.lex()

# ------------------------------------
# definitions of parsing rules by yacc
# ------------------------------------
precedence = (

    )
names = {}

def p_body(p):
    '''body : statement'''
    print '<body>' + p[1] + '</body>'

def p_state(p):
    '''statement : expression
            | statement CR statement'''
    if (len(p)==2):
        p[0] = p[1]
    elif (len(p) == 4):
        p[0] = str(p[1]) + '<br>' + str(p[3])

def p_state3(p):
    '''statement : statement CR'''
    p[0] = p[1]

def p_exp3(p):
    '''statement : LINE1
            | LINE2
            | UNLINE'''
    p[0] = '<hr>'


def p_exp5(p):
    '''expression : factor
                | factor expression'''
    if(len(p)==2):
        p[0] = p[1]
    elif(len(p)==3):
        p[0] = p[1] + p[2]

def p_exp2(p):
    '''expression : expression expression'''
    p[0] = p[1] + '\t' + p[2]

def p_exp_cr(p):
    '''expression : H1 factor
                | H2 factor
                | H3 factor'''
    if p[1] == '#':
        p[0] = '<h1>' + str(p[2]) + '</h1>'
    elif p[1] == '##':
        p[0] = '<h2>' + str(p[2]) + '</h2>'
    elif p[1] == '###': 
        p[0] = '<h3>' + str(p[2]) + '</h3>'

def p_strong(p):
    '''expression : STRONG1 factor STRONG1
                | STRONG2 factor STRONG2'''
    p[0] = '<strong>' + str(p[2]) + '</strong>'

def p_em(p):
    '''expression : EM1 factor EM1
                | EM2 factor EM2'''
    p[0] = '<em>' + str(p[2]) + '</em>'



def p_factor_text(p):
    "factor : TEXT"
    p[0] = p[1]

#def p_img(p):
 #   '''expression : IMG LINK1 factor LINK2 LINK3 factor LINK4'''
  #  p[0] = '<img src="' + str(p[6]) +'">'

def p_error(p):
    if p:
        print("error at '%s' line '%d'" % (p.value, p.lineno))
    else:
        print("error at EOF")

from ply import ply.yacc as yacc
yacc.yacc()

if __name__ == '__main__':
    filename = 'test01.md'
    yacc.parse(open(filename).read())
